﻿using System;
using System.Web.UI;
using Components.Data.UI.Controls;
using Components.Data.UI.MasterPages;

namespace Components.Data.UI
{
  public class Presentation
  {
    public Presentation()
    {
      ControlBindings = new ControlBindingCollection();
      MasterPageBindings = new MasterPageBindingCollection();
    }

    public String PageBinding { get; set; }

    public String ThemeBinding { get; set; }

    public MasterPageBindingCollection MasterPageBindings { get; set; }

    public ControlBindingCollection ControlBindings { get; set; }

    public void BindTheme(Page page)
    {
      if (!String.IsNullOrEmpty(this.ThemeBinding))
        page.Theme = this.ThemeBinding;
    }

    public void BindMasterPages(Page page)
    {
      MasterPage masterPage = null;
      MasterPageBinding masterPageBinding = this.MasterPageBindings[this.PageBinding];

      while (masterPageBinding != null)
      {
        if (masterPage == null)
        {
          masterPageBinding.BindMasterPage(page);
          masterPage = page.Master;
        }
        else
        {
          masterPageBinding.BindMasterPage(masterPage);
          masterPage = masterPage.Master;
        }

        masterPageBinding = this.MasterPageBindings[masterPageBinding.MasterPageFile];
      }
    }

    public void BindControls(Page page)
    {
      foreach (ControlBinding controlBinding in ControlBindings)
      {
        if (controlBinding.BindControl(page))
          continue;

        foreach (ControlBinding controlBindingSibling in ControlBindings)
        {
          if (controlBindingSibling == controlBinding)
            continue;

          if (controlBindingSibling.BindChildControl(controlBinding))
            break;
        }
      }
    }
  }
}